<template>
  <div>
    <div class="flex">
      <div class="flex-left">
        <div class="navigationBar">
          <label>菜单结构</label>
          <span @click="showFolder()"
            ><i class="el-icon el-icon-s-tools"></i
          ></span>
        </div>
        <div class="flex-tree">
          <el-tree
            ref="tree"
            :data="data"
            node-key="id"
            :expand-on-click-node="false"
            :render-content="renderContent"
            @node-click="handleNodeClick"
            :highlight-current="true"
          >
          </el-tree>
          <!-- lazy
						:load="loadNode" -->
        </div>
      </div>
      <div class="flex-right">
        <navigation-bar>
          <div class="searchContent">&nbsp;</div>
        </navigation-bar>
        <div class="form" v-if="type != ''">
          <el-form ref="form" :model="form" label-width="250px">
            <el-form-item label="菜单名称" required>
              <el-input v-model="form.Name"></el-input>
            </el-form-item>
            <el-form-item label="上级菜单" required>
              <el-select
                v-model="form.Pid"
                placeholder="请选择上级菜单"
                style="width: 100%"
              >
                <el-option
                  v-for="item in parentList"
                  v-bind:key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="路由地址">
              <el-input v-model="form.Code"></el-input>
            </el-form-item>
            <el-form-item label="菜单ICON名称（顶级菜单需要）">
              <el-input v-model="form.Icon"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">提交</el-button>
              <el-button>取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import navigationBar from "@/components/customComponents/managementCenter/navigationBar";
import { AjaxCommon } from "@/libs/apiCommon";
import { PopupCommon } from "@/libs/popupCommon";
import { SessionCommon } from "@/libs/sessionCommon";
export default {
  components: {
    navigationBar,
  },
  data() {
    return {
      form: {
        // 菜单名称
        Name: "",
        // 上级菜单id
        Pid: "",
        // 路由地址
        Code: "",
        // 图标地址
        Icon: "",
        Id: "",
      },
      folderData: null,
      typeFolder: "add",
      dialogFolderShow: false,
      parentId: "",
      parentList: [
        {
          value: "0",
          label: "顶级菜单",
        },
      ],
      data: [
        {
          label: "一级 1",
          children: [
            {
              label: "二级 1-1",
              children: [
                {
                  label: "三级 1-1-1",
                },
              ],
            },
          ],
        },
        {
          label: "一级 2",
          children: [
            {
              label: "二级 2-1",
              children: [
                {
                  label: "三级 2-1-1",
                },
              ],
            },
            {
              label: "二级 2-2",
              children: [
                {
                  label: "三级 2-2-1",
                },
              ],
            },
          ],
        },
        {
          label: "一级 3",
          children: [
            {
              label: "二级 3-1",
              children: [
                {
                  label: "三级 3-1-1",
                },
              ],
            },
            {
              label: "二级 3-2",
              children: [
                {
                  label: "三级 3-2-1",
                },
              ],
            },
          ],
        },
      ],
      defaultProps: {
        children: "children",
        label: "label",
      },
      tableIndex: "",
      tableList: [
        {
          id: "1",
          name: "湘江新城1",
        },
        {
          id: "2",
          name: "湘江新城2",
        },
        {
          id: "3",
          name: "湘江新城3",
        },
      ],
      selectItem: [],
      username: "",
      // table 相关参数  begin
      dataSource: [],
      tableColumns: [
        {
          prop: "useraccount",
          label: "帐号",
        },
        {
          prop: "username",
          label: "姓名",
        },
        {
          prop: "usersex",
          label: "性别",
          width: 120,
          dictName: "sex",
        },
        {
          prop: "usertel",
          label: "手机号",
        },
        {
          prop: "createtime",
          label: "创建时间",
        },
      ],
      btnList: ["edit", "delete", "resetPwd"],
      pageSize: 20,
      pageCount: 100,
      pageNo: 1,
      // table 相关参数  end

      // 弹窗是否显示
      dialogShow: false,
      // 弹窗标题 (新增修改不同)
      dialogTitle: "",
      type: "",
    };
  },
  methods: {
    onSubmit() {
      if (this.form.Code == "" || this.form.Name == "") {
        PopupCommon.notify("info", "请将信息填写完整");
        return;
      }
      let self = this;
      var params = {
        Code: this.form.Code,
        Name: this.form.Name,
        Icon: this.form.Icon,
        Pid: this.form.Pid,
      };
      var titleOpr = "新增成功";
      var url = "/api/Permission/Post";
      var requestMethod = "post";
      if (this.type == "edit") {
        params["Id"] = this.form.Id;
        titleOpr = "编辑成功";
        url = "/api/Permission/Put";
        requestMethod = "put";
      }
      AjaxCommon(url, requestMethod, params)
        .then((res) => {
          console.log(res, "res..................");
          if (res.data.status == 200) {
            PopupCommon.notify("success", titleOpr);
            self.type = "";
            self.initLeftFolder();
          } else {
            PopupCommon.notify("error", res.data.msg);
          }
        })
        .catch((err) => {
          PopupCommon.notify("error", err.message);
        });
    },
    showFolder() {
      var form = this.form;
      Object.keys(form).map((t) => {
        form[t] = "";
      });
      this.form = form;
      this.getParentMenu();
      this.type = "add";
    },

    // 懒加载获取树形结构
    loadNode(node, resolve) {
      console.log(node.level, node.data.id);
      if (node.level == 0) {
        // node其实是需要展开树节点，但是第一次的node是个无用的数据，可以认为这个node是element给我们创建的，判断的话，就是level等于0
        this.getTreeData(0, resolve);
      } else {
        this.getTreeData(node, resolve);
      }
    },
    // 获取树形结构的数据
    getTreeData(node, resolve) {
      var searchNodeID = node ? node.data.id : null;
      AjaxCommon(
        `/api/folder?folderType=4&key=${searchNodeID}`,
        "get",
        null
      ).then((res) => {
        if (res.data.status == 200) {
          var data = res.data.response;
          data = data.map((r) => {
            return {
              id: r.Id,
              label: r.FolderName,
              children: [],
            };
          });
          console.log(data, "data.......");
          if (!node) {
            return resolve(data); // resolve是一个函数，它会接受一个数组，作为你要展开的节点的孩子节点，如果没有孩子节点，直接传一个空数组
          } else {
            if (data && data.length > 0) {
              return resolve(data); // 如果需要设置一个树节点，也可以在这里设置，比如说设置这个孩子节点是叶子节点（也就是不能展开的末节点），可以给其中的数据设置item.isLeaf = true
            } else {
              return resolve([]);
            }
          }
        } else {
          PopupCommon.notify("error", res.data.msg);
        }
      });
    },
    // append(data) {
    // 	console.log(data, "data.................")
    // 	this.folderData = data
    // 	this.fatherFolderId = data.id
    // 	this.typeFolder = "add"
    // 	this.dialogFolderTitle = "新增机构"
    // 	this.dialogFolderShow = true
    // },
    remove(node, data) {
      var label = node.data.label;
      var id = data.id;
      var childNodes = data.children;
      let self = this;
      console.log(id, childNodes);
      PopupCommon.confirm(`确定删除菜单:【${label}】？`)
        .then(() => {
          AjaxCommon("/api/Permission/Delete?id=" + id, "delete", null).then(
            (res) => {
              if (res.data.status == 200) {
                console.log("删除成功");
                self.initLeftFolder();
              }
            }
          );
        })
        .catch(() => {
          console.log("取消");
        });
    },
    renderContent(h, { node, data }) {
      // <span style="color: #409EFF;padding: 2px;border-radius: 2px;margin-right: 4px;">
      // 							<i class="el-icon-plus" on-click={() => this.append(data)}></i>
      // 						</span>
      return (
        <span style="flex: 1;display: flex;align-items: center;justify-content: space-between;font-size: 14px;padding-right: 8px;">
          <span>{node.label}</span>
          <span class="tree-btn">
            <span style="padding: 2px;color: red;border-radius: 2px;">
              <i
                class="el-icon-delete"
                on-click={() => this.remove(node, data)}
              ></i>
            </span>
          </span>
        </span>
      );
    },
    initLeftFolder() {
      let self = this;
      self.data = [];
      AjaxCommon("/api/Permission/GetTreeTable", "get", null).then((res) => {
        console.log(res, "res......");
        if (res.data.status == 200) {
          var data = res.data.response;
          data = data.map((r) => {
            return {
              id: r.Id,
              label: r.Name,
              code: r.Code,
              pid: r.Pid,
              icon: r.Icon,
              children: [],
            };
          });
          self.data = data;

          // if (data && data.length > 0) {
          // 	console.log("self...............................")
          // 	self.tableIndex = data[0].id
          // 	self.$nextTick(() => {
          // 		self.$refs.tree.setCurrentKey(data[0].id)
          // 	})
          // 	callback && callback()
          // } else {
          // 	self.tableIndex = ""
          // 	self.tableList = []
          // }
        } else {
          PopupCommon.notify("error", res.data.msg);
        }
      });
    },
    handleNodeClick(e) {
      var form = this.form;
      form.Code = e.code;
      form.Icon = e.icon;
      form.Pid = e.pid;
      form.Id = e.id;
      form.Name = e.label;
      this.form = form;
      this.getParentMenu();
      this.type = "edit";
    },
    getParentMenu() {
      let self = this;
      var parentList = [
        {
          value: "0",
          label: "顶级菜单",
        },
      ];
      AjaxCommon("/api/Permission/GetTreeTable?f=0", "get", null).then(
        (res) => {
          if (res.data.status == 200) {
            var data = res.data.response;
            data.map((r) => {
              parentList.push({
                value: r.Id,
                label: r.Name,
              });
            });
            self.parentList = parentList;
          } else {
            PopupCommon.notify("error", res.data.msg);
          }
        }
      );
    },
    handleSelectionChange(d) {
      console.log(d);
    },
    formInputChange(e) {
      // if (e.filedName == "idCard") {
      // 	const data = CardId.getInfoByCardId(e.value)
      // 	if (data) {
      // 		let newData = e.allData
      // 		newData["birthday"] = data.birthday
      // 		newData["sex"] = data.sex
      // 		this.$refs.form.changeFormValue(newData)
      // 	}
      // }
      console.log(e);
    },
    formInputFolderChange(e) {
      console.log(e, "e...................");
    },
    submit(d) {
      console.log(d);
      // let self = this
      // console.log(d)
      // if (d.id) {
      // 	AjaxCommon("/ccdc/cfg/device/device/edit", "post", d)
      // 		.then((res) => {
      // 			if (res.data.code == 200) {
      // 				PopupCommon.notify("success", "操作成功")
      // 				self.initPage()
      // 				self.dialogClose()
      // 				this.dialogClose()
      // 			} else {
      // 				PopupCommon.notify("error", res.data.message)
      // 			}
      // 		})
      // 		.catch((err) => {
      // 			PopupCommon.notify("error", err.message)
      // 		})
      // } else {
      // 	delete d.id
      // 	AjaxCommon("/ccdc/cfg/device/device/add", "post", d)
      // 		.then((res) => {
      // 			if (res.data.code == 200) {
      // 				PopupCommon.notify("success", "操作成功")
      // 				self.initPage()
      // 				self.dialogClose()
      // 			} else {
      // 				PopupCommon.notify("error", res.data.message)
      // 			}
      // 		})
      // 		.catch((err) => {
      // 			PopupCommon.notify("error", err.message)
      // 		})
      // }
    },
    dialogClose() {
      this.dialogShow = false;
    },
    searchClick() {
      this.pageNo = 1;
      this.initPage();
    },
    resetClick() {
      this.username = "";
      this.usersex = "";
    },
    addClick() {
      let formConfigItem = this.formConfig;
      formConfigItem.map((t) => {
        Object.keys(t).map((res) => {
          if (res == "fieldName") {
            t.filedValue = "";
          }
        });
      });
      this.formConfig = formConfigItem;
      this.type = "add";
      this.dialogShow = true;
      this.dialogTitle =
        "新增" + JSON.parse(SessionCommon.getCurrentMenuInfo()).title;
    },
    // 分页点击事件
    pageChange(p) {
      this.pageNo = p;
      this.initPage();
    },
    editRow(d) {
      this.type = "edit";
      let formConfigItem = this.formConfig;
      formConfigItem.map((t) => {
        Object.keys(t).map((res) => {
          if (res == "fieldName") {
            t.filedValue = d.data[t[res]];
          }
        });
      });
      this.formConfig = formConfigItem;
      this.dialogShow = true;
      this.dialogTitle =
        "编辑" + JSON.parse(SessionCommon.getCurrentMenuInfo()).title;
    },
    viewRow(d) {
      this.type = "look";
      let formConfigItem = this.formConfig;
      formConfigItem.map((t) => {
        Object.keys(t).map((res) => {
          if (res == "fieldName") {
            t.filedValue = d.data[t[res]];
          }
        });
      });
      this.formConfig = formConfigItem;
      this.dialogShow = true;
      this.dialogTitle =
        "查看" + JSON.parse(SessionCommon.getCurrentMenuInfo()).title;
    },
    deleteRow(d) {
      console.log(d);
      const id = d.data.id;
      let self = this;
      AjaxCommon("/ccdc/cfg/device/device/delete?id=" + id, "delete", {
        optReason: d.optReason,
      }).then((res) => {
        console.log(res, "res...............");
        if (res.data.code == 200) {
          PopupCommon.notify("success", "删除成功");
          self.initPage();
          self.dialogClose();
        } else {
          PopupCommon.notify("error", res.data.message);
        }
      });
    },
    // 初始化事件
    initPage() {
      var dataValue = [
        {
          useraccount: "zhangsan",
          username: "张三",
          usersex: 1,
          usertel: "18684765432",
          createtime: "2024-10-11 11:12:12",
          id: 1,
        },
        {
          useraccount: "lisi",
          username: "李四",
          usersex: 1,
          usertel: "18684765432",
          createtime: "2024-10-11 11:12:12",
          id: 2,
        },
        {
          useraccount: "wangwu",
          username: "王五",
          usersex: 1,
          usertel: "18684765432",
          createtime: "2024-10-11 11:12:12",
          id: 3,
        },
      ];
      this.dataSource = dataValue;
      this.pageCount = dataValue.length;
      // let self = this
      // AjaxCommon("/ccdc/cfg/device/device/listByPage", "post", {
      // 	username: this.username,
      // 	deviceStatus: this.status,
      // 	deviceType: this.usersex,
      // 	pageNo: this.pageNo,
      // 	pageSize: this.pageSize,
      // }).then((res) => {
      // 	if (res.data.code == 200) {
      // 		self.dataSource = res.data.result.records
      // 		self.pageCount = res.data.result.total
      // 	} else {
      // 		PopupCommon.notify("error", res.data.message)
      // 	}
      // })
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initLeftFolder();
      // this.initPage()
    });
  },
};
</script>

<style scoped>
.flex {
  display: flex;
}

.flex .flex-left {
  width: 350px;
  margin-right: 10px;
}

.flex .flex-right {
  flex: 1;
}

.flex .flex-left .navigationBar {
  height: 36px;
  line-height: 36px;
  background-color: #fff;
  margin-top: 10px;
}

.flex .flex-left .flex-tree {
  background-color: #fff;
  margin-top: 10px;
  height: calc(100vh - 168px);
  overflow-y: auto;
  padding: 10px;
}

.flex .flex-left .flex-tree .tree-item {
  height: 32px;
  line-height: 32px;
  margin: 5px 10px;
  padding: 0 10px;
  font-size: 14px;
  cursor: pointer;
}
.flex .flex-left .flex-tree .tree-item:hover {
  background-color: #e4f1fe;
}
.flex .flex-left .flex-tree .hover {
  background-color: #e4f1fe;
}

.flex .flex-left .navigationBar label {
  text-align: left;
  font-size: 16px;
  color: #333;
  margin-left: 10px;
}

.flex .flex-left .navigationBar span {
  float: right;
  margin-right: 10px;
  color: #333;
  cursor: pointer;
}

.singleTable {
  margin-bottom: 20px;
}
.singleBtn {
  position: absolute;
  bottom: 8px;
  right: 9px;
}
.form {
  background-color: #fff;
  padding: 10px;
  margin-top: 10px;
}
</style>
